package com.lxf.clouduser.netty;

import com.lxf.cloudfeign.client.configsClient.ConfigClient;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 罗兴发
 * @data 2025/4/1 10:41
 * @description：webSocekt初始化
 */
@Component
@Slf4j
public class ProjectInitializer extends ChannelInitializer<SocketChannel> {
    static final String WEBSOCKET_PROTOCOL = "webSocket";
    @Resource
    ConfigClient configClient;
    @Resource
    WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        String webSocketPath = configClient.getWSPath();
        // 设置管道
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 流水线管理通道中的处理程序（Handler），用来处理业务
        // webSocket协议本身是基于http协议的，所以这边也要使用http编解码器
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ObjectEncoder());
        // 以块的方式来写的处理器
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10));
        // 自定义的handler，处理业务逻辑
        pipeline.addLast(webSocketHandler);
//        // 添加心跳处理器，例如每60秒没有读写操作则发送心跳消息
//        pipeline.addLast(new IdleStateHandler(15, 5, 0)); // 读空闲60秒，其余空闲时间设置为0秒
//        pipeline.addLast(new HeartbeatHandler()); // 自定义的心跳处理器
    }
}
